<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false">
        <a-space :size="20">
          <a-button type="primary" @click="showModal" ghost
            ><PlusCircleOutlined />新增</a-button
          >
          <a-popconfirm
            title="确认删除？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="removeBachById"
            @cancel="cancel"
          >
            <a-button :disabled="!hasSelected" type="primary" danger ghost
              ><DeleteOutlined />批量删除</a-button
            >
          </a-popconfirm>
        </a-space>
      </a-card>
    </div>

    <!-- 表格数据展示 -->
    <div class="table">
      <a-card :bordered="false">
        <div>
          <a-table
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
            :data-source="data"
            :pagination="false"
            :loading="loading"
          >
            <a-table-column
              fixed="left"
              key="image"
              title="店铺图"
              data-index="image"
            >
              <template #default="{ record }">
                <a-image
                  :preview="false"
                  style="border-radius: 10px"
                  :width="80"
                  :src="record.image"
                />
              </template>
            </a-table-column>
            <a-table-column
              key="homeName"
              title="店铺名"
              data-index="homeName"
              :ellipsis="true"
            />
            <a-table-column key="name" title="持有人" data-index="name" />
            <a-table-column
              key="idCard"
              :ellipsis="true"
              title="身份证"
              data-index="idCard"
            />
            <a-table-column
              :ellipsis="true"
              key="remark"
              title="简介"
              data-index="remark"
            />
            <a-table-column
              :ellipsis="true"
              key="address"
              title="地址"
              data-index="address"
            />
            <a-table-column key="status" title="状态">
              <template #default="{ record }">
                <span>
                  <a-tag v-if="record.status === '通过'" color="success">
                    {{ record.status }}</a-tag
                  >
                  <a-tag v-else-if="record.status === '未通过'" color="error">
                    {{ record.status }}</a-tag
                  >
                  <a-tag v-else color="processing"> {{ record.status }}</a-tag>
                </span>
              </template>
            </a-table-column>
            <a-table-column
              :ellipsis="true"
              key="reason"
              title="理由"
              data-index="reason"
            />
            <a-table-column fixed="right" key="id" title="操作">
              <template #default="{ record }">
                <div style="display: flex">
                  <div>
                    <a-popconfirm
                      title="修改后需重新审核"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="edit(record.key)"
                    >
                      <a-button type="primary" ghost><FormOutlined /></a-button>
                    </a-popconfirm>
                  </div>
                  <div style="margin-left: 10px">
                    <a-popconfirm
                      title="确认删除？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="remove(record.key)"
                      @cancel="cancel"
                    >
                      <a-button type="primary" ghost danger>
                        <DeleteOutlined href="#" />
                      </a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </a-card>
    </div>

    <!-- 新增弹出框 -->
    <div>
      <a-modal
        v-model:open="open"
        @cancel="handleCancel"
        title="新增店铺"
        :footer="null"
      >
        <div style="padding: 30px 0 20px 50px">
          <a-form
            ref="formRef"
            :model="business"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item ref="idCard" label="身份证" name="idCard">
              <a-input
                maxlength="18"
                v-model:value="business.idCard"
                size="large"
              />
            </a-form-item>
            <a-form-item ref="homeName" label="店铺名" name="homeName">
              <a-input
                placeholder="如：xxx店"
                maxlength="20"
                v-model:value="business.homeName"
                size="large"
              />
            </a-form-item>
            <a-form-item ref="regions" label="地址" name="regions">
              <a-cascader
                size="large"
                v-model:value="business.regions"
                :options="options"
                placeholder="请输入地址"
                expand-trigger="hover"
              />
            </a-form-item>
            <a-form-item ref="remark" label="店铺简介" name="remark">
              <a-textarea
                size="large"
                v-model:value="business.remark"
                :rows="4"
              />
            </a-form-item>
            <a-form-item ref="image" label="店铺图" name="image">
              <a-upload
                v-model:file-list="fileList"
                name="image"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :customRequest="customRequest"
                :before-upload="beforeUpload"
              >
                <img
                  style="height: 100px; width: 100px; border-radius: 10%"
                  v-if="business.image"
                  :src="business.image"
                  alt="avatar"
                />
                <div v-else>
                  <loading-outlined v-if="loading"></loading-outlined>
                  <plus-outlined v-else></plus-outlined>
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="save">保存</a-button>
              <a-button style="margin-left: 10px" @click="handleCancel"
                >取消</a-button
              >
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import {
  PlusCircleOutlined,
  DeleteOutlined,
  FormOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { upload } from "@/api/upload";
import { useAdminStore } from "@/stores/admin";
import {getAreaData } from "@/api/address";
import {
  saveBusiness,
  list,
  echo,
  update,
  removeBatchByKeys,
} from "@/api/store";

const adminSore = useAdminStore();
const data = ref([]);
const business = ref({
  key: null,
  idCard: "",
  homeName: "",
  remark: "",
  image: "",
  address: "",
  regions: [],
});
const loading = ref(true);
onMounted(() => {
  setTimeout(() => {
    getAllAreaData()
    getAdmins();
    loading.value = false;
  }, 1000);
});

const options = ref([]);
//获取省市区数据
function getAllAreaData() {
  getAreaData().then((res) => {
    if (res.code === 200) {
      options.value = res.data;
    }
  });
}
//请求管理员数据
function getAdmins() {
  list(adminSore.admin.key).then((res) => {
    if (res.code === 200 && res.data != null) {
      data.value = res.data;
    }
  });
}

//新增管理员弹框
const open = ref(false);
const showModal = () => {
  open.value = true;
};

//身份证号校验
let IdCardReg =
  /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
//新增管理员操作
function save() {
  formRef.value
    .validate()
    .then(() => {
      if (!IdCardReg.test(business.value.idCard)) {
        message.error("请输入正确的身份证号");
      } else {
        for (var i = 0; i < business.value.regions.length; i++) {
        business.value.address += business.value.regions[i];
      }
        //新增管理员
        if (business.value.key === null) {
          saveBusiness(business.value).then((res) => {
            if (res.code === 200) {
              message.success("新增成功！");
              //重新加载管理员数据
              getAdmins();
              open.value = false;
              business.value = {};
              business.value.key = null;
            }
          });
        } else {
          //修改管理员
          update(business.value).then((res) => {
            if (res.code === 200) {
              message.success("修改成功！");
              //重新加载管理员数据
              getAdmins();
              open.value = false;
              business.value = {};
            }
          });
        }
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增管理员操作
function handleCancel() {
  open.value = false;
  business.value = {};
}

//管理员修改操作
function edit(id) {
  echo(id).then((res) => {
    if (res.code === 200 && res.data != null) {
      business.value = res.data;
      open.value = true;
    }
  });
}

//管理员确认删除回调操作
function remove(id) {
  removeBatchByKeys(id, adminSore.admin.key).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//数据校验
const formRef = ref();
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const rules = {
  idCard: [
    {
      required: true,
      message: "请输入身份证号",
      trigger: "change",
    },
  ],
  regions: [
    {
      required: true,
      message: "请输入店铺地址",
      trigger: "change",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      min: 11,
      max: 11,
      message: "长度为11个字符",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择商户状态",
      trigger: "blur",
    },
  ],
  image: [
    {
      required: true,
      message: "请上传商户图",
      trigger: "blur",
    },
  ],
  role: [
    {
      required: true,
      message: "请输入角色",
      trigger: "blur",
    },
  ],
  homeName: [
    {
      required: true,
      message: "请输入商户名",
      trigger: "blur",
    },
  ],
  remark: [
    {
      required: true,
      message: "请输入商户简介",
      trigger: "blur",
    },
  ],
};

//存储批量商户id
const state = reactive({
  selectedRowKeys: [],
});
//当有一个或多个商户被选中时触发按钮
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//批量删除商户
const removeBachById = () => {
  setTimeout(() => {
    state.selectedRowKeys = [];
  }, 1000);
  //删除后做操作
  removeBatchByKeys(state.selectedRowKeys, adminSore.admin.key).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
};
//当选中行改变时触发
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

//头像上传部分
const fileList = ref([]);
function customRequest(file) {
  upload(file).then((res) => {
    if (res.code === 200) {
      business.value.image = res.data;
    }
  });
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("限定上传jpg/png格式!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("文件大于2MB!");
  }
  return isJpgOrPng && isLt2M;
};
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>>